package sd_services

import (
	"fmt"
	"log"
	"xiehui-service/app/models/sd_models"
	"xiehui-service/global"

	"go.uber.org/zap"
)

type dosageService struct {
}

var DosageService = new(dosageService)

// 查询耗料信息
func (dosageService *dosageService) DosageList(stamp float64, num int64) (dosages []sd_models.Dosage, err error) {
	err = global.App.MSACCESS.Ping()
	if err != nil {
		log.Println("ping==>>", err)
		global.App.Log.Error("查询耗料数据失败：", zap.Any("数据库联接", "ping失败"))
		return nil, err
	}
	rows, err := global.App.MSACCESS.Query(fmt.Sprintf("select Top %d * from Dosage where Stamp > %.10f order by Stamp asc", num, stamp))
	if err != nil {
		log.Println("query==>>", err)
		global.App.Log.Error("查询耗料数据失败：", zap.Any("Query查询失败", err))
		return nil, err
	}
	defer rows.Close()

	for rows.Next() {
		var dosageItem sd_models.Dosage

		if err := rows.Scan(&dosageItem.ID, &dosageItem.Piece, &dosageItem.StorID, &dosageItem.Storage, &dosageItem.MaterID, &dosageItem.Material, &dosageItem.Rate, &dosageItem.RecAmnt, &dosageItem.PlanAmnt, &dosageItem.FactAmnt, &dosageItem.Fall, &dosageItem.FinTim, &dosageItem.Data, &dosageItem.Flag, &dosageItem.Stamp, &dosageItem.CRC, &dosageItem.Mask, &dosageItem.ManuAmnt, &dosageItem.Temper, &dosageItem.StoneRate); err != nil {
			log.Println("scan==>>", err)
		}
		dosages = append(dosages, dosageItem)
	}

	if err := rows.Err(); err != nil {
		log.Println("rows.err==>>", err)
		global.App.Log.Error("查询耗料数据失败：", zap.Any("查询失败", err))
		return nil, err
	}

	return dosages, nil
}

// 根据Piece表的ID查询耗料信息
func (dosageService *dosageService) GetByPiece(pieceId string) (dosages []sd_models.Dosage, err error) {
	err = global.App.MSACCESS.Ping()
	if err != nil {
		log.Println("ping==>>", err)
		global.App.Log.Error("查询耗料数据失败：", zap.Any("数据库联接", "ping失败"))
		return nil, err
	}
	rows, err := global.App.MSACCESS.Query(fmt.Sprintf(`select 
	ID       
	,Piece    
	,StorID   
	,Storage  
	,MaterID  
	,Material 
	,Rate     
	,RecAmnt  
	,PlanAmnt 
	,FactAmnt 
	,Fall     
	,FinTim   
	,Data     
	,Flag     
	,Stamp    
	,CRC      
	,Mask     
	from Dosage where Piece = '%s' order by Stamp asc`, pieceId))
	if err != nil {
		log.Println("query==>>", err)
		global.App.Log.Error("查询耗料数据失败：", zap.Any("Query查询失败", err))
		return nil, err
	}
	defer rows.Close()

	for rows.Next() {
		var dosageItem sd_models.Dosage

		if err := rows.Scan(&dosageItem.ID, &dosageItem.Piece, &dosageItem.StorID, &dosageItem.Storage, &dosageItem.MaterID, &dosageItem.Material, &dosageItem.Rate, &dosageItem.RecAmnt, &dosageItem.PlanAmnt, &dosageItem.FactAmnt, &dosageItem.Fall, &dosageItem.FinTim, &dosageItem.Data, &dosageItem.Flag, &dosageItem.Stamp, &dosageItem.CRC, &dosageItem.Mask); err != nil {
			log.Println("scan==>>", err)
		}
		dosages = append(dosages, dosageItem)
	}

	if err := rows.Err(); err != nil {
		log.Println("rows.err==>>", err)
		global.App.Log.Error("查询耗料数据失败：", zap.Any("查询失败", err))
		return nil, err
	}

	return dosages, nil
}
